/*
 * @Descripttion: 
 * @version: 
 * @Author: WenQingwu
 * @Date: 2022-01-20 11:04:19
 * @LastEditors: WenQingwu
 * @LastEditTime: 2022-04-01 15:02:26
 */
let aRoleList = [] // 所有角色列表
let aUserList = [] // 所有用户列表
let aACcessList = [] // 所有权限列表
let selectedRoleId = '' //要操作的角色ID。
let checkedUser = []; //选中的用户ID
let checkedAccess = []; //选中的权限ID
let checkedUserNames = []//选中的用户name
let checkedAccessNames = [] //选中的权限name
let aUserForOneRole = []; //1个角色已绑定的所有用户
let aAccessForOneRole = [];  //1个角色已绑定的所有权限
// 添加角色后，保存时
$("#addRoleBtn").click(function () {
  let accessName = $("#accessName").val();
  let accessDes = $("#accessDes").val();

  $.ajax({
    url: '/api/addRole',
    type: 'post',
    data: { "r_name": accessName, "r_des": accessDes },
    success(res) {
      if (res.code === 0) {
        // alert(res.msg);
        // 重新加载表格数据
        getRoleList()
        // 清除表单数据
        $("#accessName").val('')
        $("#accessDes").val('')
        // 隐藏Modal
        $("#modalAddRole").modal('hide')
      } else {
        alert(res.msg)
      }
    }
  })

})

// 搜索角色
$(".searchRoleBtn").click(function () {
  // alert('查询成功')
  let searchText = $("#search").val().trim();
  getRoleList(searchText)
})


// 刷新页面数据
$(".refresh-btn").click(function () {
  location.reload()
})

// 删除角色
$("#roleTbody").on('click', '.btn-delete', function () {
  let id = $(this).parents('tr').attr('data-id');
  // console.log('删除成功' + id)
  $.ajax({
    url: '/api/delRole',
    type: 'post',
    data: { r_id: id },
    success(res) {
      if (res.code === 0) {
        getRoleList();
        // alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
})
// 添加角色成员后，保存----------------
$("#addUserToRoleBtn").click(function () {
  checkedUser = checkedUser.length === 0 ? '[]' : checkedUser;
  console.log(selectedRoleId, '///////////////////', checkedUser)
  $.ajax({
    url: '/api/addUserToRole',
    type: 'post',
    data: {
      'selectRoleId': selectedRoleId, 'userSelectedId': checkedUser
    },
    success: function (res) {
      console.log(res)
      if (res.code === 0) {
        $("#modalAddUserToRole").modal('hide')
      } else {
        alert(res.msg)
      }
    }
  })
})

// 添加角色权限后，保存-----------------
$('#addAccessToRoleBtn').click(function () {
  // alert(' 添加角色权限成功')
  console.log(selectedRoleId, '///////////////////', checkedUser)
  checkedAccess = checkedAccess.length === 0 ? '[]' : checkedAccess;
  $.ajax({
    url: '/api/addAccessForRole',
    type: 'post',
    data: { 'selectRoleId': selectedRoleId, 'accessSelectedId': checkedAccess },
    success(res) {
      if (res.code === 0) {
        console.log('成功')
        $("#modalAddAccessToRole").modal('hide')
      }else{
        alert(res.msg)
      }
    }
  })
})

// 显示设置角色成员模态框
$("#roleTbody").on('click', '.btn-add-role-to-user', async function () {
  $("#modalAddUserToRole").modal('show')
  // 设置角色名称到文本框
  $("#accessName2").val(getRoleName(this));
  // 渲染用户列表表格
  $("#userListTbody").html('')
  selectedRoleId = $(this).parents('tr').attr('data-id')
  checkedUser = [];
  checkedUserNames = []
  let str = ''
// 设置已关联的用户为选中状态

 aUserForOneRole = await getUsersForOneRole(selectedRoleId)
console.log(aUserForOneRole)
  aUserList.forEach(el => {
    str += `<tr data-id="${el.uid}">
    <td><input type="checkbox" class="checked-user"></td>
    <td>${el.uaccessno}</td>
    <td>${el.uname}</td>
  </tr>`;
  })
  $("#userListTbody").html(str)

  $('#checkedAllUser').get(0).checked = false;
  $("#selectUsers").val('')
  
})

// 显示设置角色权限模态框
$("#roleTbody").on('click', '.btn-add-role-to-access', function () {
  $("#modalAddAccessToRole").modal('show')
  // 设置角色名称到文本框
  $("#accessName3").val(getRoleName(this))
  // 渲染权限列表表格
  $("#accessTbody").html('')
  selectedRoleId = $(this).parents('tr').attr('data-id')
  checkedAccess = []
  checkedAccessNames = []
  let str = ''
  aACcessList.forEach(el => {
    str += `<tr data-id="${el.acid}">
    <td><input type="checkbox" class="checked-access"></td>
    <td>${el.acname}</td>
    <td>${el.acdes}</td>
  </tr>`;
  })
  $("#accessTbody").html(str)
  $('#checkAllAccess').get(0).checked = false;
  $("#selectAccess").val('')
})

// 全选用户成员
$("#checkedAllUser").change(function () {
  checkedUser = []
  checkedUserNames = []
  if (this.checked) {
    aUserList.forEach(el => {
      checkedUser.push(el.uid)
      checkedUserNames.push(el.uname)
    })
    $("#userListTbody input").each((i, el) => {
      // 如果给DOM节点一个CLICK（），会触发change事件，这样写不会触
      el.checked = true;
    });
  } else {
    $("#userListTbody input").each((i, el) => {
      el.checked = false;
    });
  }
  $("#selectUsers").val(checkedUserNames.toString())
})

// 全选权限数据
$("#checkAllAccess").change(function () {
  checkedAccess = []
  checkedAccessNames = []
  if (this.checked) {
    aACcessList.forEach(el => {
      checkedAccess.push(el.acid)
      checkedAccessNames.push(el.acname)
    })
    $("#accessTbody input").each((i, el) => {
      el.checked = true;
    });
  } else {

    $("#accessTbody input").each((i, el) => {
      el.checked = false;
    });
  }
  $("#selectAccess").val(checkedAccessNames.toString())
})

// 单独选中或取消一个用户
$("#userListTbody").on('change', "input", function () {
  let checkedState = this.checked;
  let uid = $(this).parents('tr').attr('data-id');

  if (checkedState == true) {
    checkedUser.push(uid)
    checkedUserNames.push(aUserList.find(el => el.uid == uid).uname)
  } else {
    checkedUser = checkedUser.filter(item => item != uid)
    checkedUserNames = checkedUserNames.filter(el => el != aUserList.find(el => el.uid == uid).uname)

  }
  console.log(checkedUser)
  $("#selectUsers").val(checkedUserNames.toString())
  // 判断是否要取消全选框
  if (checkedUser.length === aUserList.length) {
    $('#checkedAllUser').get(0).checked = true;
  } else {
    $('#checkedAllUser').get(0).checked = false;
  }
})
// 单独选中或取消一个权限
$("#accessTbody").on('change', "input", function () {
  let checkedState = this.checked;
  let acid = $(this).parents('tr').attr('data-id');

  if (checkedState == true) {
    checkedAccess.push(acid)
    checkedAccessNames.push(aACcessList.find(el => el.acid == acid).acname)
  } else {
    checkedAccess = checkedAccess.filter(item => item != acid)
    checkedAccessNames = checkedAccessNames.filter(el => el != aACcessList.find(el => el.acid == acid).acname)
  }
  console.log(checkedAccess)
  $("#selectAccess").val(checkedAccessNames.toString())
  // 判断是否要取消全选框
  if (checkedAccess.length === aACcessList.length) {
    $('#checkAllAccess').get(0).checked = true;
  } else {
    $('#checkAllAccess').get(0).checked = false;
  }

})
// 获取角色列表数据,搜索角色
function getRoleList(searchText) {
  // console.log(searchText)
  if (searchText === undefined)
    searchText = ""
  $.ajax({
    url: '/api/getRole',
    type: 'get',
    data: { searchText },
    success(res) {
      console.log(res)
      if (res.code === 0) {
        aRoleList = res.data;
        updateTable(res.data)
        // alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
}

// 更新页面表格的数据
function updateTable(arr) {
  $("#roleTbody").html('')
  let str = ''
  arr.forEach((el, i) => {
    str += `<tr data-id="${el.r_id}">
    <td>
      <input type="checkbox">
    </td>
    <td>${el.r_name}</td>
    <td class="text-muted">${el.r_des}</td>
    <td>
      <div class="custom-control custom-switch">
        <input type="checkbox" class="custom-control-input" id="customSwitch${i}" ${el.r_state === "1" ? 'checked' : ''} data-id="${el.r_id}">
        <label class="custom-control-label" for="customSwitch${i}">${el.r_state === "0" ? '禁用' : '启用'}</label>
      </div>
    </td>
    <td>
      <button type="button" class="btn btn-link text-success btn-add-role-to-user" >角色成员</button>
      <button type="button" class="btn btn-link text-warning btn-add-role-to-access" >角色权限</button>
      <button type="button" class="btn btn-link text-danger btn-delete">删除</button>
    </td>
  </tr>`;
  })
  $("#roleTbody").append(str)
}
// 修改角色状态
function modifyRoleate(r_id, r_state) {
  $.ajax({
    url: '/api/modifyAccessState',
    type: 'post',
    data: { r_id, r_state },
    success(res) {
      if (res.code === 0) {
        alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
}

// 获取所有的用户信息数据
function getUsers() {
  $.ajax({
    url: '/api/getUsers',
    type: 'get',
    success(res) {
      if (res.code === 0) {
        aUserList = res.data;
        console.log(aUserList)
        // alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
}

// 获取权限列表数据
function getAccess() {
  $.ajax({
    url: '/api/getAccess',
    type: 'get',
    data: { searchText: '' },
    success(res) {
      if (res.code === 0) {
        aACcessList = res.data;
        console.log(aACcessList)
        // alert(res.msg)
      } else {
        alert(res.msg)
      }
    }
  })
}

// 拿tr上的角色Id,并得到角色Name,只用于页面表格中的CRUD操作按钮，不可用于Modal。
function getRoleName(dom) {
  let r_id = $(dom).parents('tr').attr('data-id');

  let oRole = aRoleList.find(el => el.r_id === parseInt(r_id))

  return oRole.r_name;

}
// 获取一个角色的所有已关联的成员
function getUsersForOneRole(selectedRoleId){
 return new Promise((resolve,reject)=>{
    $.ajax({
      url:'/api/getUsersForOneRole',
      type:'get',
      data:{rid:selectedRoleId},
      success(res){
        if(res.code === 0){
          resolve(res.data)
        }else{
          reject(res.msg)
        }
      }
    })
  })
}
// 获取一个角色的所有已关联的权限
function getUsersForOneRole(selectedRoleId){
  return new Promise((resolve,reject)=>{
     $.ajax({
       url:'/api/getAccessForOneRole',
       type:'get',
       data:{rid:selectedRoleId},
       success(res){
         if(res.code === 0){
           resolve(res.data)
         }else{
           reject(res.msg)
         }
       }
     })
   })
 }
// 给表格中的状态做事件委托
$("#roleTbody").on('change', '.custom-control-input', function () {
  let r_state = "0"

  if (this.checked) {
    $(this).next().text('启用')
    // $(this).val("1")
    r_state = "1"
  } else {
    $(this).next().text('禁用')
    // $(this).val("0")
  }
  modifyRoleate($(this).parents('tr').attr('data-id'), r_state)
})
// 默认请求列表数据
$(document).ready(function () {
  // 获取列表数据
  getRoleList();
  getUsers()
  getAccess()
})


